package com.winit.common.util;

import com.winit.common.handler.CmdOutputHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by wangjian on 16/1/16.
 * 运行shell命令工具类
 */
public class ShellRunUtil {

    static final Logger log = LoggerFactory.getLogger(ShellRunUtil.class);

    /**
     * 拼接参数
     *
     * @param cmds
     * @return
     */
    public static String[] getShellParam(String... cmds) {
        String[] param = new String[cmds.length];
        for (int i = 0; i < cmds.length; i++) {
            param[i] = cmds[i];
        }
        return param;
    }

    public static Map<String, Object> runCmds(String... cmds) {
        StringBuffer command = new StringBuffer();
        for (int i = 0; i < cmds.length; i++) {
            command.append(cmds[i]).append(" ");
        }

        String[] param = getShellParam("bash", Constants.SHELL_PATH + "shell/beetle_doshell.sh", command.toString());
        return ShellRunUtil.runShell(param);
    }

    public static Map<String, Object> runShell(String[] param) {
        StringBuffer str = new StringBuffer();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 1);
        try {
            Process process = Runtime.getRuntime().exec(param);
            BufferedInputStream in = new BufferedInputStream(process.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                str.append(line).append(",");
                log.info("com.winit.common.util.ShellRunUtil.runShell 返回：" + line);
            }
            if (!StringUtils.isEmpty(str.toString())) {
                map.put("message", str.toString().substring(0, str.toString().length() - 1));
            } else {
                map.put("message", "");
            }
            int result = process.waitFor();
            map.put("code", result);
            br.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("com.winit.common.util.ShellRunUtil.runShell . param=" + Arrays.toString(param) + ",map=" + map);
        return map;
    }
}
